<template>
	<view >
		<ChooseType :typeId="currentTypeId" :typeName="currentTypeName" @changeType="changeType"></ChooseType>
		<view >
			
			<uni-card :is-shadow="false">
				<view class="uni-body"  >
					<uni-easyinput type="textarea" id="title" autoHeight v-model="title" :inputBorder="false" placeholder="" />
				</view>
				<view slot="actions" class="card-actions">
					<view class="card-actions-item" @click="openDeleteTitleConfirm()">
						<uni-icons type="trash" size="18" color="#999"></uni-icons>
						<text class="card-actions-item-text">删除全部</text>
					</view>
					<view class="card-actions-item" @click="copyTitle()">
						<uni-icons type="map" size="18" color="#999"></uni-icons>
						<text class="card-actions-item-text">复制</text>
					</view>
					<view class="card-actions-item" @click="updateTitle()">
						<uni-icons type="compose" size="18" color="#999"></uni-icons>
						<text class="card-actions-item-text">保存</text>
					</view>
				</view>
			</uni-card>
			
			<hr style="width:90%;margin:0 auto;background-color:#aaa; height:0.5px; border:none;"/>
			
			<uni-card :is-shadow="false" v-for="(item,index) in contents" :key="index">
				<template v-if="item.content!=''">
					<view class="uni-body"  >
						<uni-easyinput type="textarea"  autoHeight v-model="item.content" :inputBorder="false" placeholder="" />
					</view>
					<view slot="actions" class="card-actions">
						<view class="card-actions-item" @click="openDeleteConfirm(item.cid)">
							<uni-icons type="trash" size="18" color="#999"></uni-icons>
							<text class="card-actions-item-text">删除</text>
						</view>
						<view class="card-actions-item" @click="copyContent(index)">
							<uni-icons type="map" size="18" color="#999"></uni-icons>
							<text class="card-actions-item-text">复制</text>
						</view>
						<view class="card-actions-item" @click="updateContent(index)">
							<uni-icons type="compose" size="18" color="#999"></uni-icons>
							<text class="card-actions-item-text">保存</text>
						</view>
					</view>
				</template>
				<template v-if="item.file!=''">
					<view class="uni-body"  >
						<img :src = "item.file" width="100%">
					</view>
					<view slot="actions" class="card-actions">
						<view class="card-actions-item" @click="openDeleteConfirm(item.cid)">
							<uni-icons type="trash" size="18" color="#999"></uni-icons>
							<text class="card-actions-item-text">删除</text>
						</view>
						<!-- <view class="card-actions-item" @click="download(item.file)">
							<uni-icons type="compose" size="18" color="#999"></uni-icons>
							<text class="card-actions-item-text">下载</text>
						</view> -->
					</view>
				</template>
			</uni-card>
			
			<hr style="width:90%;margin:0 auto;background-color:#aaa; height:0.5px; border:none;"/>
			
			<uni-card :is-shadow="false">
				<uni-easyinput type="textarea" autoHeight v-model="newContent" placeholder="内容" />
				<view slot="actions" class="card-actions">
					<view style="text-align: right;margin-right: 10px;" @click="chooseImageAndUpload()">
						<uni-icons type="compose" size="18" color="#999"></uni-icons>
						<text class="card-actions-item-text">上传图片</text>
					</view>
					<view  style="text-align: right;margin-right: 10px;" @click="add()">
						<uni-icons type="compose" size="18" color="#999"></uni-icons>
						<text class="card-actions-item-text">保存</text>
					</view>
				</view>
			</uni-card>
			<br>
		</view>
		
		<uni-popup ref="deleteConfirm" type="dialog">
			<uni-popup-dialog type="info" cancelText="关闭" confirmText="确认" title="确认" content="您确认删除吗？" @confirm="recycleContentById"></uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="deleteTitleConfirm" type="dialog">
			<uni-popup-dialog type="info" cancelText="关闭" confirmText="确认" title="确认" content="您确认全部删除吗？" @confirm="recycleNoteById"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import {getNoteByTid,addContent,recycleContentById,recycleTitleById,updateTitleById,updateContentById,updateTypeById} from '@/api/note.js'
	import ChooseType from '@/components/ChooseType.vue'
	import {BASEURL} from '@/utils/request.js'
	
	export default {
		components: {
			ChooseType,
		},
		data() {
			return {
				title: '',
				contents:[],
				newContent:"",
				tid:"",
				deleteCid:"", // 准备删除笔记的cid
				currentTypeName:"",
				currentTypeId:"",
			};
		},
		onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
			// console.log(option.tid) //打印出上个页面传递的参数。
			this.tid = option.tid
			setTimeout(() => {
				uni.startPullDownRefresh();
			},100)
		},
		onBackPress:function(event){
			if (event.from === 'navigateBack') {  
				return false;  
			}  
			this.back()
			return true
		},
		onPullDownRefresh() { // 响应下拉事件
			this.getNoteByTid()
		},
		methods: {
			getNoteByTid(){
				getNoteByTid(this.tid).then( res => {
					// console.log("res:",res)
					if(res.code === 0){
						this.contents = res.data.notes
						this.title = res.data.title
						this.currentTypeId = res.data.typeId
						this.currentTypeName = res.data.typeName
						// console.log(this.currentTypeId,this.currentTypeName)
						uni.stopPullDownRefresh();
					}
				})
			},
			
			contentId(id){
				return "content_"+id
			},
			add(){ // 添加内容
				if(this.newContent === ""){
					uni.showToast({
						icon: 'none',
						title: '请输入内容！',
					});
					return
				}
				addContent(this.tid, this.newContent,this.currentTypeId).then(res => {
					// console.log("res:",res)
					this.pushContents(
						res.data.cid,
						this.newContent,
						"",
						res.data.create_time,
						res.data.modify_time
					)
					this.newContent = ""
				})
			},
			copyContent(index){
				// console.log(this.contents[index].content)
				
				uni.setClipboardData({
					data: this.contents[index].content ,
					success: function () {
						uni.showToast({
							title: '复制成功',
						});
					},
					fail:function () {
						uni.showToast({
							title: '复制失败',
						});
					}
				});
			},
			copyTitle(){
				uni.setClipboardData({
					data: this.title ,
					success: function () {
						uni.showToast({
							title: '复制成功',
						});
					},
					fail:function () {
						uni.showToast({
							title: '复制失败',
						});
					}
				});
			},
			openDeleteConfirm(id){ // 打开删除确认框
				// console.log("recycleContentById(id):",id)
				this.deleteCid = id
				this.$refs.deleteConfirm.open()
			},
			recycleContentById(){ // 将内容删除到回收站
				const id = this.deleteCid
				recycleContentById(id).then(res=>{
					
						
					for(let i = 0,len = this.contents.length;i<len;i++){
						// console.log("item:",this.contents[i])
						// console.log("item cid:",this.contents[i].cid)
						if( this.contents[i].cid == id){
							this.contents.splice(i, 1)
							break
						}
					}
					
					
					uni.showToast({
						title: res.msg,
					});
					
					this.deleteCid = "" // 清空要删除笔记的cid
					
				})
			},
			
			openDeleteTitleConfirm(){ // 显示删除笔记标题、全部内容对话框
				
				this.$refs.deleteTitleConfirm.open()
			},
			recycleNoteById(){ // 删除笔记标题、全部内容
				recycleTitleById(this.tid).then(res => {
					uni.showToast({
						title: res.msg,
					});
					setTimeout( () =>{
						this.back()
					},800)
					
				})
			},
			updateTitle(){
				updateTitleById(this.tid,this.title).then(res => {
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
				})
			},
			updateContent(index){
				const cid = this.contents[index].cid
				const content = this.contents[index].content
				updateContentById(cid,content).then(res => {
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
				})
			},
			changeType(typeId,typeName){
				// console.log("new changeType:",typeId,typeName)
				this.currentTypeId = typeId
				this.currentTypeName = typeName
				updateTypeById(this.tid,typeId).then( res => {
					if(res.code !== 0){
						uni.showToast({
							icon: 'none',
							title: res.msg
						})
					}
				})
			},
			back(){
				uni.setStorageSync('index_ajax_type', "update_notes_notetypes")
				uni.navigateBack({
					delta: 1,
					// success: () => {
					// 	const eventChannel = this.getOpenerEventChannel();
					// 	eventChannel.emit('navReloadEvent');
					// }
				})
			},
			/**
			 * 选中图片并上传
			 */
			chooseImageAndUpload(){
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						console.log("tempFilePaths:",chooseImageRes)
						uni.uploadFile({
							url: BASEURL+'/note/upload', 
							filePath: tempFilePaths[0],
							name: 'image',
							formData:{
								tid:this.tid, 
								typeId:this.currentTypeId
							},
							success: (res) => {
								const data = JSON.parse(res.data)
								// console.log(data);
								if(data.code == 0){
									this.pushContents(
										data.cid,
										"",
										data.data.file,
										data.data.create_time,
										data.data.modify_time
									)
								}else{
									uni.showToast({
										icon: 'none',
										title: data.msg
									})
								}
							}
						});
					}
				});
			},
			/**
			 * 下载
			 * @param {Object} url
			 */
			download(url){
				uni.downloadFile({
					url: url, //仅为示例，并非真实的资源
					success: (res) => {
						if (res.statusCode === 200) {
							// console.log('下载成功');
						}
					}
				});
			},
			/**
			 * 向contents数组追加数据
			 * @param {Object} cid
			 * @param {Object} content
			 * @param {Object} file
			 * @param {Object} create_time
			 * @param {Object} modify_time
			 */
			pushContents(cid,content,file,create_time,modify_time){
				this.contents.push({
					cid: cid,
					content: content,
					file:file,
					create_time: create_time,
					modify_time: modify_time,
				})
			}
		},
		onNavigationBarButtonTap(e) {
			// console.log(e.text);//提交
			if(e.text === '新建'){
				uni.navigateTo({
					url: './note/new'
				});
			}
			
		}
	};
</script>

<style scoped>
	
	.card-actions {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;
		height: 45px;
		border-top: 1px #eee solid;
	}
	.card-add {
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: right;
		height: 45px;
		border-top: 1px #eee solid;
	}
	.card-actions-item {
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.card-button-item{
		display: flex;
		flex-direction: row;
		align-items: right;
		
	}
	.card-actions-item-text {
		font-size: 12px;
		color: #666;
		margin-left: 5px;
	}
	
</style>
